function toSrc(pic) {
	return ' src="/static/' + schoolId + '/' + field + '/' + pic + '"';
}

tinymce.PluginManager.add('imageSelector', function (editor, url) {
	function addImg(pic) {
		editor.insertContent('<img' + toSrc(pic) + ' />');
	}

	editor.ui.registry.addButton('imageSelector', {
		icon: 'image',
		tooltip: '插入图片',
		onAction: function () {
			if (/micromessenger/.test(navigator.userAgent.toLowerCase())) {
				wxChooseImg(9, field, addImg);
				return;
			}

			var file = document.getElementById('file');
			file.onchange = function () {
				axios.post('/pc/upload/' + field + '?schoolId=' + schoolId,
					new FormData(document.getElementById('form'))).then(function (res) {
						addImg(res.data.data);
					});
			};
			file.click();
		}
	});
});

var tinymceInit = {
	language: 'zh_CN',
	language_url: '/js/zh_CN.js',
	menubar: false,
	statusbar: false,
	contextmenu: false,
	content_style: 'img{max-width:90vw}',
	plugins: 'imageSelector paste preview autolink code visualblocks visualchars fullscreen link table charmap hr nonbreaking advlist lists noneditable charmap emoticons',
	toolbar: 'fullscreen | undo redo | imageSelector emoticons charmap table link blockquote | superscript subscript bold italic underline strikethrough | forecolor backcolor removeformat | fontsizeselect fontselect formatselect | alignleft aligncenter alignright alignjustify alignnone | outdent indent | numlist bullist | visualblocks preview',
	paste_data_images: true
};

function getText(html) {
	var div = document.createElement('div');
	div.innerHTML = html;
	var a = div.innerText;
	div.remove();
	return a;
}

function replaceImg(obj, field1) {
	var reg = / src="data:image\/(\w+);base64,([^"]+)"/g;
	var group = reg.exec(obj[field1]);
	if (!group) {
		if (obj[field1].length > 10000)
			axios.post('/api/report', { 'html过大': obj[field1] }).then(function (res) { });
		return;
	}

	var bytes = atob(group[2]);
	var ab = new ArrayBuffer(bytes.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < bytes.length; i++)
		ia[i] = bytes.charCodeAt(i);
	var fd = new FormData();
	fd.append('file', new Blob([ab], { type: 'image/' + group[1] }), 'a.' + group[1]);
	axios.post('/pc/upload/' + field + '?schoolId=' + schoolId, fd).then(function (res) {
		obj[field1] = obj[field1].replace(group[0], toSrc(res.data.data));
	});
};